package com.lg.algorithm.leetcode;

import java.util.Random;

/**
 * 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
 *
 * 请你将两个数相加，并以相同形式返回一个表示和的链表。
 *
 * 你可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 *
 * 输入：l1 = [2,4,3], l2 = [5,6,4]
 * 输出：[7,0,8]
 * 解释：342 + 465 = 807.
 *
 * 输入：l1 = [0], l2 = [0]
 * 输出：[0]
 *
 * 输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 * 输出：[8,9,9,9,0,0,0,1]
 *
 * 提示：
 *  每个链表中的节点数在范围 [1, 100] 内
 *  0 <= Node.val <= 9
 *  题目数据保证列表表示的数字不含前导零
 *
 *  这道需要注意的是
 *  在最后如果有进位 那么需要输出 出来
 *
 *  https://leetcode-cn.com/problems/add-two-numbers/
 *
 */
public class AddTwoNum {

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int nextNum = 0;
        int l1Num = 0;
        int l2Num = 0;
        ListNode res = null;
        ListNode iNext = null;
        boolean headFlag = true;
        while (true) {
            if (l1 == null && l2 == null) {
                if (nextNum > 0) {
                    iNext.next = new ListNode(nextNum);
                }
                break;
            }

            if (l1 != null) {
                l1Num = l1.val;
                l1 = l1.next;
            } else {
                l1Num = 0;
            }
            if (l2 != null) {
                l2Num = l2.val;
                l2 = l2.next;
            }else {
                l2Num = 0;
            }

            int tarNum = l1Num + l2Num + nextNum;
            if (headFlag) {
                res = new ListNode(tarNum % 10);
                iNext = res;
                nextNum = tarNum / 10;
                headFlag = false;
                continue;
            }
            iNext.next = new ListNode(tarNum % 10);
            iNext = iNext.next;
            nextNum = tarNum / 10;
        }
        return res;
    }

    public static ListNode createList(int nodeNum){
        Random random = new Random();
        ListNode res = null;
        ListNode iNext = null;
        for (int i = 0; i < nodeNum; i++) {
            if (i == 0) {
                res = new ListNode(random.nextInt(8) + 1);
                iNext = res;
            } else {
                iNext.next  = new ListNode(random.nextInt(8)+1);
                iNext = iNext.next;
            }
        }
        return res;
    }
    public static void printListNode(ListNode listNode){
        do {
            System.out.print(listNode.val + " --> ");
            listNode = listNode.next;
        } while (listNode != null);
        System.out.println("null");
    }
    public static void main(String[] args) {
        int num = 3;
//        System.out.println(1/10);
        ListNode l1 = createList(num);
        ListNode l2 = createList(num);

        printListNode(l1);
        printListNode(l2);
        printListNode(addTwoNumbers(l1,l2));
    }
}

class ListNode{
        int val;
        ListNode next;
        ListNode(int n){
            this.val = n;
        }
}